package io.github.veigara.tcp.device.protocol.charger;

import com.google.common.primitives.Bytes;
import io.netty.buffer.ByteBuf;
import lombok.Data;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @author : zhouhx
 * 充电机消息
 * @date : 2025/6/6 13:55
 */
@Data
public class ChargingPileMessage {
    /**
     * 起始域
     */
    private int startFlag = 0xAAF5;
    /**
     * 长度域
     */
    private int length;
    /**
     * 信息域
     */
    private byte infoField;
    /**
     * 序列号域
     */
    private byte sequence;
    /**
     * 命令代码
     */
    private int cmd;
    /**
     * 数据域
     */
    private ByteBuf data;
    /**
     * 校验和域
     */
    private int checksum;
    /**
     * 原始代码
     */
    private String sourceHex;

    public int calculateChecksum() {
        // 校检对象：命令代码和数据域
        byte[] cmdBytes = ByteBuffer.allocate(4)
                .order(ByteOrder.LITTLE_ENDIAN)
                .putInt(cmd)
                .array();

        byte[] checkSumData = Bytes.concat(cmdBytes, getBytes(data));

        int sum =0;
        for (byte b: checkSumData) {
            sum += b;
        }

        return sum & 0xFF;
    }

    public byte[] getBytes(ByteBuf data) {
        data.resetReaderIndex();
        byte[] dataBytes = new byte[data.readableBytes()];
        data.readBytes(dataBytes);
        return dataBytes;
    }
}
